package operate.node;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * @author m0v1
 * @date 2021年09月07日 7:39 上午
 */
public class CreateNode extends AbstractNodeOperation {

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("client connect to server");

            try {
                System.out.println("begin to create nodes...");
                createNodes();
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 节点创建
     * @throws KeeperException
     * @throws InterruptedException
     */
    private void createNodes() throws KeeperException, InterruptedException {
        // 创建永久节点
        String permanentNode = zooKeeper.create(
                "/zk-create-permanent-node-by-api",
                "from api".getBytes(),
                // 节点创建的权限信息(4种类型)
                // ANYONE_ID_UNSAFE:表示任何⼈
                // AUTH_IDS:此ID仅可⽤于设置ACL。它将被客户机验证的ID替换
                // OPEN_ACL_UNSAFE:完全开放的ACL(常⽤)-->world:anyone
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT
        );

        // 创建持久顺序节点
        String permanentSequentialNode = zooKeeper.create(
                "/zk-create-permanent-sequential-node-by-api",
                "from api".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT_SEQUENTIAL
        );

        // 创建临时节点
        String ephemeralNode = zooKeeper.create(
                "/zk-create-ephemeral-node-by-api",
                "from api".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL
        );

        // 创建临时顺序节点
        String ephemeralSequentialNode = zooKeeper.create(
                "/zk-create-ephemeral-sequential-node-by-api",
                "from api".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL
        );
        System.out.println("current permanent node is :" + permanentNode);
        System.out.println("current permanent sequential node is :" + permanentSequentialNode);
        System.out.println("current ephemeral node is :" + ephemeralNode);
        System.out.println("current ephemeral sequential node is :" + ephemeralSequentialNode);
    }
}
